package org.yw.controller;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created By YU WEI on 2020.09.09
 */
@Component
public class TokenFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getHeader("token");
        String requestURI = request.getRequestURI();
        if(requestURI.contains("/v/")){
            if(token == null){
                context.setSendZuulResponse(false);
                context.setResponseBody("用户未登录，请去登录。。。");
                context.setResponseStatusCode(403);
                context.addZuulResponseHeader("content-type","text/html;charset=utf-8");
                return null;
            }
        }
        System.out.println("请求地址放行。。。");
        return null;
    }
}
